package com.hmall.item.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemServiceClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.dto.RequestParams;
import com.hmall.item.config.MqConstants;
import com.hmall.item.service.searchService;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class searchServiceImpl implements searchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    ItemServiceClient itemServiceClient;
    /**
     *实现基本搜索功能
     * @param params
     * @return
     */
    @Override
    public PageDTO<ItemDoc> seach(RequestParams  params) {
        try {
        //1. 场建request
        SearchRequest resquest = new SearchRequest("item");
        buildBasicQuery(params,resquest);
      // 2.2 分页
        Integer page = params.getPage();
        Integer size = params.getSize();
        resquest.source().from((page -1) * size).size(size);
         //2.3 排序
            String sortBy = params.getSortBy();
              if ("sold".equals(sortBy)){
                 resquest.source().sort(sortBy, SortOrder.DESC);
              }else if ("price".equals(sortBy)){
                resquest.source().sort(sortBy,SortOrder.ASC);
              }

              // 发送请求
            SearchResponse response = restHighLevelClient.search(resquest, RequestOptions.DEFAULT);
            return handleResponse(response);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    //实现基本搜索功能结果解析
    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        SearchHits outerHits = response.getHits();
        //总条数
        long total = outerHits.getTotalHits().value;

        // 4.2 文档数组
        SearchHit[] hits = outerHits.getHits();
     List<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit innerHit : hits) {
            String sourceAsString = innerHit.getSourceAsString();
         //4.3反序列化weiDoc 对象
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
          // 处理高亮
            Map<String, HighlightField> highlightFields = innerHit.getHighlightFields();
             if (!highlightFields.isEmpty()){
                 HighlightField field = highlightFields.get("name");
                  if (field != null){
                      String name = field.getFragments()[0].string();
                      itemDoc.setName(name);
                  }
             }

            itemDocs.add(itemDoc);
        }
     //4.4 F 封装 返回
        return new PageDTO(total,itemDocs);
    }

    /**
     * 实现基本搜索功能封装查询条件
     * @param params
     * @param resquest
     */
    private void buildBasicQuery(RequestParams params, SearchRequest resquest) {
        //1.构建Boolean
        //作为算分原始查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
         //2. 关键字搜索
        String key = params.getKey();
          if (key == null ||"".equals(key)){
             boolQuery.must(QueryBuilders.matchAllQuery());
          }else {
              boolQuery.must(QueryBuilders.matchQuery("all",key));
          }
         //3.条件搜索
        String category = params.getCategory();
        if (category != null && !category.equals("")){
          boolQuery.filter(QueryBuilders.matchQuery("category",category));
         }
        /*if (!category.isEmpty()){

        }*/

        // 4. 品牌条件
        String brand = params.getBrand();
         if (brand != null && !brand.equals("")){
            boolQuery.filter(QueryBuilders.matchQuery("brand",brand));
         }

        // 5 价格
         //最小
        Integer minPrice = params.getMinPrice();
        //最大
        Integer maxPrice = params.getMaxPrice();

         if (minPrice != null && maxPrice !=null){
             //范围
              boolQuery.filter(QueryBuilders
                      .rangeQuery("price")
                      .gte(params.getMinPrice())
                      .lte(params.getMaxPrice())
              );
         }
      // 7. 算法控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                // function score 数据
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        // 其中的一个function score 元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAd", true),
                                // 算分函数  这个里面用的是 权重
                                ScoreFunctionBuilders.weightFactorFunction(10)

                        )
                }
        );
       //8. termQuery
        resquest.source().query(functionScoreQuery);

    }


    /**
     *  自动补全功能
     * @param prefx
     * @return
     */
    @Override
    public List<String> getSuggestions(String prefx) {
        //创建一个字符串列表
        List<String> list = new ArrayList<>();
        //1.创建 Request
        //创建搜索请求，查询名为"item"的索引
        SearchRequest request = new SearchRequest("item");
//        2.准备DSL
        //准备DSL并添加建议器
        request.source().suggest(new SuggestBuilder().addSuggestion("suggestions",
                //创建完整建议器
                SuggestBuilders.completionSuggestion("suggestion")
                        //设置查询前缀
                        .prefix(prefx)
                        //设置是否跳过重复项
                        .skipDuplicates(true)
                        //设置建议器结果数量
                        .size(10)
        ));
        // 3.发起请求
        try {
            //发起搜索请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            //4. 解析结果    //获取建议结果
            Suggest suggest = response.getSuggest();
            //获取完整建议结果
            CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
            for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
                //遍历建议结果中的选项
                list.add(option.getText().string());
            }
            //返回结果列表
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     *过滤项聚合功能
     * @param requestParams
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.query
            buildBasicQuery(requestParams, request);
            // 2.2.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();

            Aggregations aggregations = response.getAggregations();

            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            // 4.2.根据分类名称，获取品牌结果
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    // 定义,品牌, 分类
    private void buildAggregation(SearchRequest request) {
//        品牌
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );

    }
    //结果解析
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }


    /**
     *  新增
     * @param id
     */

    @Override
    public void inserById(Long id) {
        try {
            // 0,根据id 查询商城数据
            Item item = itemServiceClient.getById(id);
            //转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);
            //1.准备Request
            IndexRequest request = new IndexRequest("item").id(item.getId().toString());
            //2.准备 JSON 文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            //发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleById(Long id) {
        //准备Request
        DeleteRequest request = new DeleteRequest("item",id.toString());
        //准备发送请求
        try {
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
